const mongoose = require('mongoose');

// 数据库配置
const dbConfig = {
  development: {
    uri: 'mongodb://localhost:27017/dongning',
    options: {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      maxPoolSize: 10,
      serverSelectionTimeoutMS: 5000,
      socketTimeoutMS: 45000,
    }
  },
  production: {
    uri: process.env.MONGODB_URI || 'mongodb://dongning:wangle321@39.96.171.44:27017/dongning',
    options: {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      maxPoolSize: 50,
      serverSelectionTimeoutMS: 10000,
      socketTimeoutMS: 45000,
      family: 4, // 使用IPv4，避免连接问题
      retryWrites: true,
      w: 'majority',
      readPreference: 'primary',
      // 生产环境连接池配置
      minPoolSize: 5,
      maxIdleTimeMS: 30000,
      waitQueueTimeoutMS: 10000,
    }
  }
};

const env = process.env.NODE_ENV || 'development';
const config = dbConfig[env];

// 连接数据库
const connectDB = async () => {
  try {
    console.log(`正在连接到 ${env} 环境数据库...`);
    console.log(`数据库URI: ${config.uri.replace(/\/\/.*@/, '//***:***@')}`); // 隐藏密码
    
    await mongoose.connect(config.uri, config.options);
    
    console.log(`✅ ${env} 环境数据库连接成功!`);
    
    // 监听连接事件
    mongoose.connection.on('error', (err) => {
      console.error('❌ 数据库连接错误:', err);
    });
    
    mongoose.connection.on('disconnected', () => {
      console.warn('⚠️  数据库连接断开');
    });
    
    mongoose.connection.on('reconnected', () => {
      console.log('✅ 数据库重新连接成功');
    });
    
    // 优雅关闭
    process.on('SIGINT', async () => {
      await mongoose.connection.close();
      console.log('📴 数据库连接已关闭');
      process.exit(0);
    });
    
  } catch (error) {
    console.error('❌ 数据库连接失败:', error);
    process.exit(1);
  }
};

module.exports = {
  connectDB,
  mongoose
};